import asyncio
import json
import logging
import os
import tempfile
from typing import Dict, List, Optional, Any
from datetime import datetime
from playwright.async_api import async_playwright, Browser, BrowserContext, Page
from app.core.config import settings
from app.services.storage_service import storage_service

logger = logging.getLogger(__name__)


class XiaohongshuService:
    """小红书自动化服务"""
    
    def __init__(self):
        self.browser: Optional[Browser] = None
        self.context: Optional[BrowserContext] = None
        self.page: Optional[Page] = None
        self.playwright = None
        self.user_data_dir = os.path.join(os.path.expanduser("~"), ".cool-red-browser-data")
        self.is_initialized = False
        self.login_info: Optional[Dict] = None
        self.max_pages = 5  # 最大页面数限制
        self.active_pages: List[Page] = []  # 跟踪活跃页面
        
    async def initialize(self) -> bool:
        """初始化浏览器"""
        try:
            if self.is_initialized and self.browser:
                try:
                    # 检查浏览器是否仍然可用
                    pages = self.browser.pages
                    if not pages or not pages[0]:
                        self.is_initialized = False
                except Exception:
                    # 如果浏览器连接断开，重新初始化
                    self.is_initialized = False
                
            if self.is_initialized:
                return True
                
            logger.info("初始化Firefox浏览器...")
            
            # 确保用户数据目录存在
            os.makedirs(self.user_data_dir, exist_ok=True)
            
            self.playwright = await async_playwright().start()
            
            # 使用Firefox浏览器，持久化用户数据
            self.browser = await self.playwright.firefox.launch_persistent_context(
                user_data_dir=self.user_data_dir,
                headless=False,  # 强制显示窗口
                args=[
                    '--new-instance',
                    '--no-remote'
                ],
                viewport={'width': 1200, 'height': 800},
                slow_mo=500  # 添加延迟，确保操作稳定
            )
            
            # 获取或创建页面
            pages = self.browser.pages
            if pages:
                self.page = pages[0]
            else:
                self.page = await self.browser.new_page()
                
            self.context = self.browser
                
            self.is_initialized = True
            # 初始化时清理多余页面
            await self._cleanup_excess_pages()
            logger.info("Firefox浏览器初始化完成，使用持久化上下文")
            return True
            
        except Exception as e:
            logger.error(f"浏览器初始化失败: {e}")
            await self._cleanup_on_error()
            return False
    
    async def open_login_page(self) -> Dict[str, Any]:
        """打开登录页面并获取二维码"""
        try:
            if not await self.initialize():
                return {"success": False, "message": "浏览器初始化失败"}
                
            logger.info("打开小红书登录页面...")
            await self.page.goto('https://creator.xiaohongshu.com/login', 
                                wait_until='networkidle', 
                                timeout=settings.PLAYWRIGHT_TIMEOUT)
            
            # 等待页面加载完成
            await asyncio.sleep(2)
            
            # 尝试点击二维码登录按钮
            try:
                # 首先尝试点击指定的xpath元素来切换到二维码登录模式
                qr_switch_xpath = '//*[@id="page"]/div/div[2]/div[1]/div[2]/div/div/div/div/img'
                try:
                    await self.page.wait_for_selector(f'xpath={qr_switch_xpath}', timeout=5000)
                    await self.page.click(f'xpath={qr_switch_xpath}')
                    logger.info(f"成功点击二维码切换按钮: {qr_switch_xpath}")
                    # 等待切换完成
                    await asyncio.sleep(2)
                except Exception as xpath_error:
                    logger.warning(f"使用xpath点击失败: {xpath_error}，尝试其他选择器")
                    
                    # 备用选择器
                    qr_selectors = [
                        'text=APP扫一扫登录',
                        '[data-testid="qr-login"]',
                        '.qr-login-btn',
                        'button:has-text("扫码登录")',
                        'button:has-text("二维码登录")',
                        '.login-qr-btn',
                        'img[src*="qr"]',
                        '.qr-code-switch',
                        '.switch-qr'
                    ]
                    
                    qr_button_found = False
                    for selector in qr_selectors:
                        try:
                            await self.page.wait_for_selector(selector, timeout=3000)
                            await self.page.click(selector)
                            logger.info(f"成功点击二维码登录按钮: {selector}")
                            qr_button_found = True
                            break
                        except:
                            continue
                    
                    if not qr_button_found:
                        logger.warning("未找到二维码登录按钮，可能已经显示二维码")
                
                # 等待二维码加载
                await asyncio.sleep(3)
                
                # 截取二维码
                qr_image_url = await self._capture_qr_code()
                
                return {
                    "success": True, 
                    "message": "登录页面已打开，二维码已生成",
                    "qr_code_url": qr_image_url
                }
                
            except Exception as qr_error:
                logger.error(f"处理二维码失败: {qr_error}")
                return {
                    "success": True, 
                    "message": "登录页面已打开，但二维码获取失败，请手动完成登录"
                }
            
        except Exception as e:
            logger.error(f"打开登录页面失败: {e}")
            return {"success": False, "message": str(e)}
    
    async def _capture_qr_code(self) -> Optional[str]:
        """截取二维码并保存为静态文件"""
        try:
            # 首先尝试使用精确的二维码xpath
            qr_code_xpath = '//*[@id="page"]/div/div[2]/div[1]/div[2]/div/div/div/div/div/div[2]/img'
            qr_element = None
            
            try:
                qr_element = await self.page.wait_for_selector(f'xpath={qr_code_xpath}', timeout=5000)
                if qr_element:
                    logger.info(f"找到二维码元素: {qr_code_xpath}")
            except Exception as xpath_error:
                logger.warning(f"使用xpath定位二维码失败: {xpath_error}，尝试其他选择器")
                
                # 备用的二维码选择器
                qr_selectors = [
                    'img[src*="qr"]',
                    '.qr-code img',
                    '.qr-code canvas',
                    '[class*="qr"] img',
                    '[class*="qrcode"] img',
                    'canvas[width="200"]',
                    'canvas[width="180"]',
                    '.login-qr img',
                    '.qr-login img'
                ]
                
                for selector in qr_selectors:
                    try:
                        qr_element = await self.page.wait_for_selector(selector, timeout=2000)
                        if qr_element:
                            logger.info(f"找到二维码元素: {selector}")
                            break
                    except:
                        continue
            
            if not qr_element:
                # 如果找不到特定的二维码元素，截取整个登录区域
                logger.warning("未找到二维码元素，尝试截取登录区域")
                login_selectors = [
                    '.login-container',
                    '.login-form',
                    '.login-panel',
                    '.login-box'
                ]
                
                for selector in login_selectors:
                    try:
                        qr_element = await self.page.wait_for_selector(selector, timeout=2000)
                        if qr_element:
                            break
                    except:
                        continue
            
            # 创建静态文件目录
            static_dir = os.path.join(os.getcwd(), "static", "qr_codes")
            os.makedirs(static_dir, exist_ok=True)
            
            # 生成唯一的文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"qr_code_{timestamp}.png"
            file_path = os.path.join(static_dir, filename)
            
            # 截图
            if qr_element:
                await qr_element.screenshot(path=file_path)
                logger.info(f"成功截取二维码元素")
            else:
                # 如果还是找不到元素，截取整个页面的一部分
                logger.warning("使用备用截图方案")
                await self.page.screenshot(path=file_path, clip={'x': 700, 'y': 150, 'width': 200, 'height': 200})
            
            # 返回可访问的URL
            qr_url = f"/static/qr_codes/{filename}"
            logger.info(f"二维码已保存: {file_path}")
            return qr_url
            
        except Exception as e:
            logger.error(f"截取二维码失败: {e}")
            return None
    
    async def check_login_status(self) -> Dict[str, Any]:
        """检查登录状态"""
        try:
            if not self.is_initialized:
                if not await self.initialize():
                    return {"success": False, "is_logged_in": False, "message": "浏览器初始化失败"}
            
            # 等待页面加载
            await self.page.wait_for_load_state('networkidle', timeout=10000)
            
            current_url = self.page.url
            logger.info(f"当前URL: {current_url}")
            
            # 如果页面是空白，先导航到小红书
            if current_url in ['about:blank', '']:
                logger.info("页面为空白，导航到小红书...")
                await self.page.goto('https://creator.xiaohongshu.com', 
                                    wait_until='networkidle', 
                                    timeout=settings.PLAYWRIGHT_TIMEOUT)
                current_url = self.page.url
                logger.info(f"导航后URL: {current_url}")
            
            # 检查是否在登录页面
            is_on_login_page = 'login' in current_url
            
            if is_on_login_page:
                return {"success": True, "is_logged_in": False, "message": "仍在登录页面，未登录"}
            
            # 检查是否在创作者中心页面
            is_on_creator_page = (
                'creator.xiaohongshu.com' in current_url and 
                'login' not in current_url and 
                any(keyword in current_url for keyword in ['creator', 'dashboard', 'publish', 'new/home'])
            )
            
            if is_on_creator_page:
                return {"success": True, "is_logged_in": True, "message": "已登录，在创作者中心页面"}
            
            # 检查页面内容
            page_content = await self.page.content()
            
            # 检查是否有登录相关元素
            has_login_elements = any(keyword in page_content for keyword in ['login', '登录', '手机号', '验证码'])
            
            # 检查是否有创作者中心元素
            has_creator_elements = any(keyword in page_content for keyword in [
                '创作者', '发布', '数据', 'dashboard', 'publish', 'new/home', '笔记管理', '数据看板'
            ])
            
            if has_creator_elements and not has_login_elements:
                return {"success": True, "is_logged_in": True, "message": "已登录，检测到创作者中心元素"}
            
            if has_login_elements:
                return {"success": True, "is_logged_in": False, "message": "未登录，检测到登录元素"}
            
            return {"success": True, "is_logged_in": False, "message": "登录状态不明确"}
            
        except Exception as e:
            logger.error(f"检查登录状态时出错: {e}")
            return {"success": False, "is_logged_in": False, "message": str(e)}
    
    async def get_login_info(self) -> Dict[str, Any]:
        """获取登录信息"""
        try:
            # 检查登录状态
            status_result = await self.check_login_status()
            
            if not status_result.get("is_logged_in", False):
                return {"success": False, "message": "用户未登录"}
            
            # 导航到创作者主页
            logger.info("导航到创作者主页获取用户信息...")
            await self.page.goto('https://creator.xiaohongshu.com/new/home', wait_until='networkidle')
            await self.page.wait_for_timeout(3000)
            
            # 获取cookies
            cookies = await self.context.cookies()
            
            # 根据xpath.md中的定位方式获取用户信息
            nickname = None
            following = None
            followers = None
            account_name = None
            
            try:
                # 获取昵称
                try:
                    nickname_selector = '#content-area > main > div:nth-child(3) > div > div.left > div:nth-child(1) > div.personal > div.base > div.text > div:nth-child(1) > div'
                    nickname_element = await self.page.query_selector(nickname_selector)
                    if nickname_element:
                        nickname = await nickname_element.text_content()
                        nickname = nickname.strip() if nickname else None
                        logger.info(f"获取到昵称: {nickname}")
                except Exception as e:
                    logger.warning(f"获取昵称失败: {e}")
                
                # 获取关注数
                try:
                    following_xpath = '//*[@id="content-area"]/main/div[3]/div/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/span[1]'
                    following_element = await self.page.query_selector(f'xpath={following_xpath}')
                    if following_element:
                        following = await following_element.text_content()
                        following = following.strip() if following else "0"
                        logger.info(f"获取到关注数: {following}")
                except Exception as e:
                    logger.warning(f"获取关注数失败: {e}")
                
                # 获取粉丝数
                try:
                    followers_xpath = '//*[@id="content-area"]/main/div[3]/div/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/span[1]'
                    followers_element = await self.page.query_selector(f'xpath={followers_xpath}')
                    if followers_element:
                        followers = await followers_element.text_content()
                        followers = followers.strip() if followers else "0"
                        logger.info(f"获取到粉丝数: {followers}")
                except Exception as e:
                    logger.warning(f"获取粉丝数失败: {e}")
                
                # 获取账号名
                try:
                    account_xpath = '//*[@id="content-area"]/main/div[3]/div/div[1]/div[1]/div[1]/div[1]/div[2]/div[3]/div[1]'
                    account_element = await self.page.query_selector(f'xpath={account_xpath}')
                    if account_element:
                        account_text = await account_element.text_content()
                        if account_text:
                            # 去掉"小红书账号:"前缀
                            account_name = account_text.replace("小红书账号:", "").strip()
                            logger.info(f"获取到账号名: {account_name}")
                except Exception as e:
                    logger.warning(f"获取账号名失败: {e}")
                    
            except Exception as e:
                logger.warning(f"获取用户信息时出错: {e}")
            
            # 保存登录信息
            self.login_info = {
                "nickname": nickname,
                "account_name": account_name,
                "following": following or "0",
                "followers": followers or "0",
                "cookies": cookies,
                "login_time": datetime.now().isoformat()
            }
            
            return {
                "success": True,
                "message": "登录信息获取成功",
                "data": {
                    "nickname": nickname,
                    "account_name": account_name,
                    "following": following or "0",
                    "followers": followers or "0",
                    "cookies": json.dumps(cookies),
                    "title": await self.page.title(),
                    "url": self.page.url
                }
            }
            
        except Exception as e:
            logger.error(f"获取登录信息时出错: {e}")
            return {"success": False, "message": str(e)}
    
    async def publish_post(self, title: str, content: str, images: List[str] = None) -> Dict[str, Any]:
        """发布图文内容"""
        try:
            logger.info(f"开始小红书自动化发布流程: {title}")
            
            if not self.is_initialized:
                if not await self.initialize():
                    return {"success": False, "message": "浏览器初始化失败"}
            
            # 检查登录状态
            status_result = await self.check_login_status()
            if not status_result.get("is_logged_in", False):
                return {"success": False, "message": "用户未登录，请先登录"}
            
            # 使用页面管理机制获取或创建发布页面
            logger.info("获取或创建发布页面...")
            publish_page = await self._get_or_create_page('https://creator.xiaohongshu.com/publish/publish')
            await publish_page.wait_for_timeout(3000)
            
            # 使用获取的页面进行后续操作
            current_page = publish_page
            
            # 等待页面加载完成
            logger.info("等待页面加载完成...")
            await current_page.wait_for_selector('body', timeout=5000)
            
            # 点击上传图文
            upload_selectors = [
                '.creator-tab:has-text("上传图文")',
                'div.creator-tab:has(.title:has-text("上传图文"))',
                'button:has-text("上传图文")',
                'a:has-text("上传图文")',
                '.creator-tab'
            ]
            
            upload_tab = None
            for selector in upload_selectors:
                try:
                    element = current_page.locator(selector).first
                    if await element.is_visible(timeout=2000):
                        upload_tab = element
                        logger.info(f"找到上传图文按钮，选择器: {selector}")
                        break
                except:
                    continue
            
            if upload_tab:
                try:
                    await upload_tab.scroll_into_view_if_needed()
                    await current_page.wait_for_timeout(1000)
                    await upload_tab.click(timeout=10000)
                    logger.info("点击了上传图文按钮")
                    await current_page.wait_for_timeout(2000)
                except Exception as e:
                    logger.warning(f"点击上传图文按钮失败: {e}")
                    try:
                        await upload_tab.evaluate('el => el.click()')
                        logger.info("JavaScript点击成功")
                        await current_page.wait_for_timeout(2000)
                    except Exception as js_error:
                        logger.error(f"JavaScript点击也失败: {js_error}")
            
            # 等待页面跳转到图文上传界面
            await current_page.wait_for_timeout(3000)
            
            # 上传图片（如果有）
            if images and len(images) > 0:
                logger.info("开始上传图片...")
                file_input_selectors = [
                    'input[type="file"].upload-input',
                    'input[type="file"][accept*=".jpg"]',
                    'input[type="file"][accept*="image"]',
                    'input[type="file"]'
                ]
                
                file_input = None
                for selector in file_input_selectors:
                    try:
                        element = current_page.locator(selector).first
                        if await element.count() > 0:
                            file_input = element
                            logger.info(f"找到文件上传输入框，选择器: {selector}")
                            break
                    except:
                        continue
                
                if file_input:
                    try:
                        # 下载图片到本地临时文件
                        local_images = []
                        temp_files = []
                        
                        for image_url in images:
                            if image_url.startswith('http'):
                                # 如果是完整URL，直接使用
                                local_images.append(image_url)
                            else:
                                # 如果是对象存储路径，下载到本地
                                temp_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False)
                                temp_file.close()
                                
                                if storage_service.download_file(image_url, temp_file.name):
                                    local_images.append(temp_file.name)
                                    temp_files.append(temp_file.name)
                                else:
                                    logger.warning(f"Failed to download image: {image_url}")
                        
                        if local_images:
                            await file_input.set_input_files(local_images)
                            logger.info(f"已上传 {len(local_images)} 张图片")
                            await current_page.wait_for_timeout(3000)
                        
                        # 清理临时文件
                        for temp_file in temp_files:
                            try:
                                os.unlink(temp_file)
                            except:
                                pass
                                
                    except Exception as e:
                        logger.error(f"图片上传失败: {e}")
            
            # 等待页面元素加载完成
            await current_page.wait_for_timeout(2000)
            
            # 输入标题
            logger.info("查找标题输入框...")
            title_selectors = [
                'input[placeholder*="标题"]',
                'input[placeholder*="请输入标题"]',
                '.title-input input',
                '.el-input__inner[placeholder*="标题"]',
                'input.el-input__inner'
            ]
            
            title_input = None
            for selector in title_selectors:
                try:
                    element = current_page.locator(selector).first
                    if await element.is_visible(timeout=2000):
                        title_input = element
                        logger.info(f"找到标题输入框，选择器: {selector}")
                        break
                except:
                    continue
            
            if title_input:
                try:
                    await title_input.fill(title)
                    logger.info("已输入标题")
                except Exception as e:
                    logger.error(f"标题输入失败: {e}")
            
            # 输入内容
            logger.info("查找内容输入框...")
            content_selectors = [
                'textarea[placeholder*="内容"]',
                'textarea[placeholder*="请输入内容"]',
                '.content-input textarea',
                '.el-textarea__inner',
                'textarea.el-textarea__inner',
                'div[contenteditable="true"]'
            ]
            
            content_input = None
            for selector in content_selectors:
                try:
                    element = current_page.locator(selector).first
                    if await element.is_visible(timeout=2000):
                        content_input = element
                        logger.info(f"找到内容输入框，选择器: {selector}")
                        break
                except:
                    continue
            
            if content_input:
                try:
                    await content_input.fill(content)
                    logger.info("已输入内容")
                except Exception as e:
                    logger.error(f"内容输入失败: {e}")
            
            # 查找发布按钮
            logger.info("查找发布按钮...")
            publish_button_selectors = [
                'button:has-text("发布")',
                '.publish-btn',
                '.el-button--primary:has-text("发布")',
                '[class*="publish"]:has-text("发布")',
                '.submit-btn'
            ]
            
            publish_button = None
            for selector in publish_button_selectors:
                try:
                    element = current_page.locator(selector).first
                    if await element.is_visible(timeout=2000):
                        publish_button = element
                        logger.info(f"找到发布按钮，选择器: {selector}")
                        break
                except:
                    continue
            
            if publish_button:
                try:
                    await publish_button.click()
                    logger.info("已点击发布按钮")
                    # 等待发布完成
                    await current_page.wait_for_timeout(5000)
                    logger.info("发布操作已完成")
                    
                    # 关闭发布页面
                    await publish_page.close()
                    
                    return {
                        "success": True,
                        "message": "发布成功",
                        "data": {
                            "title": title,
                            "content": content,
                            "publish_time": datetime.now().isoformat()
                        }
                    }
                    
                except Exception as e:
                    logger.error(f"点击发布按钮失败: {e}")
                    await publish_page.close()
                    return {"success": False, "message": f"点击发布按钮失败: {e}"}
            else:
                await publish_page.close()
                return {"success": False, "message": "未找到发布按钮"}
                
        except Exception as e:
            logger.error(f"小红书发布失败: {e}")
            return {"success": False, "message": str(e)}
    
    async def _cleanup_excess_pages(self):
        """清理多余的页面，防止内存泄漏"""
        try:
            if not self.browser:
                return
                
            pages = self.browser.pages
            if len(pages) <= self.max_pages:
                return
                
            logger.info(f"检测到 {len(pages)} 个页面，超过最大限制 {self.max_pages}，开始清理...")
            
            # 保留主页面和最近创建的页面
            pages_to_close = pages[1:-1] if len(pages) > 2 else []
            
            for page in pages_to_close:
                try:
                    if not page.is_closed():
                        await page.close()
                        logger.info("已关闭一个多余页面")
                except Exception as e:
                    logger.warning(f"关闭页面失败: {e}")
                    
            # 更新活跃页面列表
            self.active_pages = [page for page in self.browser.pages if not page.is_closed()]
            logger.info(f"页面清理完成，当前活跃页面数: {len(self.active_pages)}")
            
        except Exception as e:
            logger.error(f"清理多余页面失败: {e}")
    
    async def _get_or_create_page(self, url: str = None) -> Page:
        """获取或创建页面，确保不超过最大页面数"""
        try:
            # 先清理多余页面
            await self._cleanup_excess_pages()
            
            # 检查是否有可重用的页面
            if self.browser:
                pages = self.browser.pages
                for page in pages:
                    try:
                        if not page.is_closed():
                            current_url = page.url
                            # 如果页面是空白页或者是目标URL，可以重用
                            if current_url in ['about:blank', 'chrome://newtab/'] or (url and current_url == url):
                                if url:
                                    await page.goto(url, wait_until='networkidle')
                                return page
                    except Exception:
                        continue
            
            # 如果没有可重用的页面，创建新页面
            if len(self.browser.pages) >= self.max_pages:
                # 强制清理最老的页面（除了主页面）
                pages = self.browser.pages
                if len(pages) > 1:
                    try:
                        await pages[1].close()
                        logger.info("强制关闭最老页面以释放资源")
                    except Exception as e:
                        logger.warning(f"强制关闭页面失败: {e}")
            
            new_page = await self.browser.new_page()
            if url:
                await new_page.goto(url, wait_until='networkidle')
            
            self.active_pages.append(new_page)
            logger.info(f"创建新页面，当前活跃页面数: {len(self.browser.pages)}")
            return new_page
            
        except Exception as e:
            logger.error(f"获取或创建页面失败: {e}")
            # 降级到使用主页面
            if self.page and not self.page.is_closed():
                if url:
                    await self.page.goto(url, wait_until='networkidle')
                return self.page
            raise
    
    async def _cleanup_on_error(self):
        """错误时清理资源"""
        try:
            if self.browser:
                await self.browser.close()
            if self.playwright:
                await self.playwright.stop()
        except Exception as e:
            logger.error(f"清理资源失败: {e}")
        finally:
            self.browser = None
            self.context = None
            self.page = None
            self.playwright = None
            self.is_initialized = False
            self.active_pages.clear()  # 清理活跃页面列表
    
    async def close(self):
        """关闭浏览器（保持持久化上下文）"""
        try:
            # 对于持久化上下文，我们不完全关闭浏览器
            # 只是清理多余页面，保持主页面运行以维持登录状态
            if self.browser:
                try:
                    pages = self.browser.pages
                    if pages:
                        logger.info("浏览器保持运行状态以维持登录状态")
                        # 清理多余页面，只保留主页面
                        await self._cleanup_excess_pages()
                        # 进一步确保只保留一个主页面
                        remaining_pages = self.browser.pages
                        if len(remaining_pages) > 1:
                            for page in remaining_pages[1:]:
                                try:
                                    if not page.is_closed():
                                        await page.close()
                                        logger.info("关闭额外页面")
                                except Exception as e:
                                    logger.warning(f"关闭页面失败: {e}")
                        
                        # 更新活跃页面列表
                        self.active_pages = [page for page in self.browser.pages if not page.is_closed()]
                        logger.info(f"页面清理完成，保留 {len(self.active_pages)} 个页面")
                    else:
                        await self._cleanup_on_error()
                        logger.info("浏览器已关闭")
                except Exception:
                    await self._cleanup_on_error()
                    logger.info("浏览器已关闭")
        except Exception as e:
            logger.error(f"关闭浏览器失败: {e}")
            await self._cleanup_on_error()
    
    async def force_close(self):
        """强制关闭浏览器"""
        try:
            if self.browser:
                await self.browser.close()
            if self.playwright:
                await self.playwright.stop()
            self.browser = None
            self.context = None
            self.page = None
            self.playwright = None
            self.is_initialized = False
            self.active_pages.clear()  # 清理活跃页面列表
            logger.info("浏览器已强制关闭")
        except Exception as e:
            logger.error(f"强制关闭浏览器失败: {e}")


# 创建全局实例
xiaohongshu_service = XiaohongshuService()